package com.wn.ticket.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class UploadUtils {

    @Value("${upfile.filePath}")
    private String FilePath;

    public String filesUpload(MultipartFile[] files) {
        List<String> list = new ArrayList<String>();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                list = saveFile(file, list);// 保存文件
            }
        }
        return String.join(",", list);
    }

    private List<String> saveFile(MultipartFile file, List<String> list) {
        if (!file.isEmpty()) {  // 判断文件是否为空
            try {
                //String filepath="E:\\TestUpdatafile";
               /*String filePath = request.getSession().getServletContext()
                        .getRealPath("/")
                        + "upload/" + file.getOriginalFilename();*/
                String filePath = FilePath + "\\" + "upload/" + file.getOriginalFilename();
                list.add(file.getOriginalFilename());
                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                // 转存文件
                file.transferTo(saveDir);
                return list;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
